package megrez.oss.local.config;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import megrez.oss.common.ErrorResponse;
import megrez.oss.common.FileEmptyException;
import megrez.oss.common.FileNameException;
import megrez.oss.common.OSSException;
import megrez.oss.local.utils.FileExistException;
import megrez.oss.local.utils.FileNotFoundExcepiton;
import megrez.oss.local.utils.FileUnReadableException;
import megrez.oss.local.utils.MetadataNotFoundException;

/**
 * 统一异常处理
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
    private static final String MESSAGE_TEMPLATE = "业务异常 - {}";

    @ExceptionHandler({ FileEmptyException.class, FileExistException.class, FileNameException.class,
            FileUnReadableException.class })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleBadRequest(OSSException e) {
        return handleOSSException(e);
    }

    @ExceptionHandler({ FileNotFoundExcepiton.class, MetadataNotFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(OSSException e) {
        return handleOSSException(e);
    }

    public ErrorResponse handleOSSException(OSSException e) {
        ErrorResponse rslt = new ErrorResponse();
        rslt.setClazz(e.getClass().getName());
        rslt.setError(e.getMessage());
        rslt.getParams().addAll(e.getParams());

        if (log.isDebugEnabled()) {
            log.debug(MESSAGE_TEMPLATE, rslt);
        }
        return rslt;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleInternalServerError(Exception e) {
        log.error("系统异常", e);

        ErrorResponse rslt = new ErrorResponse();
        rslt.setClazz(e.getClass().getName());
        rslt.setError(e.getMessage());
        return rslt;
    }
}